<template>
  <div>
    <div class="header" :style="{height:this.$store.getters.offsetWidth?95 + 'px':'12vh'}">
      <div class="logo" :class="{ 'is-active': isActive }">
        <img src="@/assets/images/login_logo_03.png" alt="" height="50px" />
        <div class="text">众益信息发布管理系统</div>
      </div>
      <div class="navbar">
        <div class="btn" :class="{ 'is-active': isActive }" @click="handleMenu">
          <span :class="menuBtn"></span>
        </div>
        <div style="display: flex; margin-right: 10px">
            <div style="margin-right: 10px;padding-top: 30px;" v-if="Invoking.forFunctionCode('userNotify:selectPage')">
              <el-badge is-dot class="item" v-if="notRead != 0"><i class="el-icon-bell" style="font-size: 20px;" @click="openMessage"></i></el-badge>
              <i v-if="notRead===0" class="el-icon-bell" style="font-size: 20px;" @click="openMessage"></i>
            </div>

            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                <div style="text-align: right; margin-right: 10px;padding-top: 10px;display: inline-grid;">
                  <!-- <div>{{this.$store.getters.username}}</div> -->
                  <div>{{ ruleForm.userName }}</div>
                  <div>{{ ruleForm.roleName }}</div>
                </div>
                <img style="width: 50px;height: 50px;border-radius: 25px;margin-right: 10px" src="@/assets/images/user.jpg" />
                <div style="padding-top: 20px;display: inline-grid;"><i class="el-icon-arrow-down el-icon--right"></i></div>
              </span>
              <el-dropdown-menu
                slot="dropdown"
                style="margin-left: 40px; text-align: center"
              >
              <el-dropdown-item
                icon="el-icon-s-custom"
                @click.native="clickpersonalData"
                >个人资料</el-dropdown-item
              >
              <el-dropdown-item
                icon="el-icon-s-tools"
                @click.native="putPassWodr = true"
                >修改密码</el-dropdown-item
              >
              <el-dropdown-item @click.native="logout">退出 </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

        </div>

      </div>
    </div>
    <el-dialog
      title="个人资料"
      :visible.sync="personalDataDialog"
      :width="this.$store.getters.offsetWidth"
      v-dialogDrag
      ref="dialog__wrapper"
      :close-on-click-modal="false"
    >
      <div class="dialog-body">
        <div class="line">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="ruleForm.userName"></el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="ruleForm.realName"></el-input>
            </el-form-item>
            <el-form-item
              label="部门"
              prop="departmentName"
              width="100%"
              v-if="ruleForm.departmentName"
            >
              <el-select
                v-model="ruleForm.departmentName"
                disabled
                placeholder="请选择活动区域"
              >
                <el-option
                  :label="item.departmentName"
                  :value="item.departmentId"
                  v-for="item in department"
                  :key="item.departmentId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系方式" prop="userMobphone">
              <el-input v-model="ruleForm.userMobphone"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="info" class="auditOpinion">
              <el-input
                type="textarea"
                v-model="ruleForm.info"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="" prop="" class="auditOpinion">
              <el-switch
                v-model="warnStatus"
                active-text="开启预警"
                inactive-text="关闭预警" @change="warnStatusChange">
              </el-switch>
            </el-form-item>
          </el-form>
          <span
            style="
              width: 100%;
              text-align: center;
              margin: 20px auto 0;
              height: 50px;
              display: block;
            "
            class="button_dialog"
          >
            <el-button
              style="background-color: #4d9ce0; color: #fff"
              @click="submitInformation"
              >确 定</el-button
            >
            <el-button @click="personalDataDialog = false">取 消</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="修改密码"
      :visible.sync="putPassWodr"
      :width="this.$store.getters.offsetWidth"
      v-dialogDrag
      ref="dialog__wrapper"
      @close="closePutPassWodr"
      :close-on-click-modal="false"
    >
      <div class="dialog-body">
        <div class="line">
          <el-form ref="form" label-width="100px">
            <el-form-item label="原始密码">
              <el-input
                placeholder="请输入原始密码"
                v-model="passwodr.originalPassWodr"
                show-password
                maxlength="16"
              ></el-input>
            </el-form-item>
            <el-form-item label="新密码">
              <el-input
                placeholder="请再次输入新密码"
                v-model="passwodr.passwordConfirm1"
                show-password
                maxlength="16"
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码">
              <el-input
                placeholder="请再次输入新密码"
                v-model="passwodr.passwordConfirm2"
                show-password
                maxlength="16"
              ></el-input>
            </el-form-item>
          </el-form>
          <span
            style="
              width: 100%;
              text-align: center;
              margin: 0 auto;
              height: 50px;
              display: block;
            "
            class="button_dialog"
          >
            <el-button style="background-color: #4d9ce0; color: #fff"
               @click="SubmitThePassword">确 定</el-button
            >
            <el-button>清 空</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
export default {
  name: "Header",
  data() {
    return {
      personalDataDialog: false,
      putPassWodr: false,
      menuBtn: "el-icon-newfont-caidan",
      ruleForm: "",
      department: "",
      roleOptions: "",
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        userMobphone: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
      },
      passwodr: {
        originalPassWodr: "",
        passwordConfirm1: "",
        passwordConfirm2: "",
      },
      uid: localStorage.getItem("uid"),
      dialogWidth:'',
      warnStatus:false,
      websocket:"",
      sock_path:"",
      activeClose:0,
      maxReconnect:0,
      notRead:0
    };
  },
  computed: {
    // 如果左侧菜单打开，则旋转btn180度
    isActive() {

      return !this.$store.getters.sidebar.opened;
    },
  },
  mounted() {
    this.personalData();
    this.getWidth();
  },
  created(){
    this.sock_path = String(this.$http.defaults.baseURL).substr(String(this.$http.defaults.baseURL).indexOf(":"));
    let warnstatus2 = window.sessionStorage.getItem("warnNotice");
    if(warnstatus2 == 1){
      this.connectionSk();
    }
    //this.selectCount();
  },
  methods: {
    ...mapMutations({
      bindLogout: "BIND_LOGOUT",
      getWidth:'GET_WIDTH'
    }),
    // 提交用户信息修改
    async submitInformation() {
      let formData = new FormData();
      formData.append("uid", this.uid);
      formData.append("userName", this.ruleForm.userName);
      formData.append("realName", this.ruleForm.realName);
      formData.append("userMobphone", this.ruleForm.userMobphone);
      const { data: res } = await this.$http.post(
        "sysUser/updateByPrimaryKey2",
        formData
      );
      if (res.result == "success") {
        this.$message({
          type: "success",
          message: res.message,
        });
      } else {
        this.$message({
          type: "error",
          message: res.message,
        });
      }
      this.personalDataDialog = false;
      this.personalData();
    },
    // 关闭弹窗
    closePutPassWodr() {
      this.passwodr.originalPassWodr = "";
      this.passwodr.passwordConfirm1 = "";
      this.passwodr.passwordConfirm2 = "";
      // this.putPassWodr = false;
    },
    clickpersonalData() {
      this.personalData();
      let warnstatus2 = window.sessionStorage.getItem("warnNotice");
      if(warnstatus2 == 1){
        this.warnStatus = true;
      }
      this.personalDataDialog = true;
    },
    async personalData() {
      let formData = new FormData();
      let formData1 = new FormData();
      formData.append("uid", this.uid);
      const { data: res } = await this.$http.post(
        "sysUser/selectByPrimaryKey",
        formData
      );
      const { data: res1 } = await this.$http.post(
        "dictionary/selectDepartment",
        formData1
      );
      const { data: res2 } = await this.$http.post(
        "roles/selectRoleInfo",
        formData1
      );
      this.userName = res.data.userName;
      this.roleName = res.data.roleName;
      this.department = res1.data;
      this.roleOptions = res2.data;
      this.ruleForm = res.data;
    },
    handleMenu() {
      this.$store.dispatch("ToggleSideBar");
      this.$emit('resizeSideBar',this.isActive)
    },
    // 登出
    logout() {
      this.$confirm("是否退出账户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let formData = new FormData();
          const { data: res } = await this.$http.post(
            "sysUser/backLoginOut",
            formData
          );
          this.$message.success(res.message);
          this.bindLogout();
          this.$router.push({
            path: "/login",
          });
        })
        .catch(() => {});
    },
    // 修改密码
    async SubmitThePassword() {
      if (this.passwodr.passwordConfirm1 !== this.passwodr.passwordConfirm2) {
        this.$message({
          type: "warning",
          message: "新密码与确定密码不一致",
        });
        // this.closePutPassWodr();
        return;
      }
      if (
        this.passwodr.passwordConfirm1.length < 6 ||
        this.passwodr.passwordConfirm1.length < 6
      ) {
        this.$message({
          type: "warning",
          message: "密码长度不能低于6位",
        });

        return;
      }
      let formData = new FormData();
      let token = window.sessionStorage.getItem("token");
      formData.append("zycmToken", token);
      formData.append("oldPassword", this.passwodr.originalPassWodr);
      formData.append("newPassword", this.passwodr.passwordConfirm1);
      const { data: res } = await this.$http.post(
        "sysUser/updatePwd",
        formData
      );
      if (res.result == "success") {
        this.$message({
          type: "success",
          message: res.message,
        });
        this.logout();
        this.putPassWodr = false;
        this.closePutPassWodr();
      } else {
        this.$message({
          type: "error",
          message: res.message,
        });
      }
    },
    //初始化websocket
    connectionSk(){
      //开启实时消息接收
      if ('WebSocket' in window) {//判断浏览器是否支持WebSocket
            this.websocket = new WebSocket("ws"+this.sock_path+"websocket/connectServer");
        }
        else if ('MozWebSocket' in window) {
            this.websocket = new MozWebSocket("ws"+this.sock_path+"websocket/connectServer");
        }
        else {
            this.websocket = new SockJS("http"+this.sock_path+"sockjs/connectServer");
        }
        this.websocket.onopen = this.onWsOpen;
        this.websocket.onmessage = this.onWsMessage;
        this.websocket.onerror = this.onWsError;
        this.websocket.onclose = this.onWsClose;
    },
    onWsOpen(result) {
      this.warnStatus = true;
    },
    onWsMessage(result) {
        //alert("客户端接收服务端数据时触发:"+result.data); 弹窗
        //let a = 0;

        //setInterval(()=>{if(a < 3){this.warnWin(result);a++}},2000)
      this.warnWin(result);
        //刷新数据
      //$("#main_frame")[0].src = $("#main_frame")[0].src;
    },
    onWsError(result) {
      //console.log("socket通信发生错误!");
      //$("#notice_win").attr("checked",false);
      this.warnStatus = false;
     /*  $("#notice_win")[0].checked = false;
      form.render("checkbox");
      $("#notice_win").next().css({"margin-top":"0px"}); */
      //connectionSk();
    },
    onWsClose(result) {
      //alert("连接关闭时触发:"+result.data);
      //重连
      if(this.activeClose==0){
        if(this.maxReconnect <= 50){
          this.connectionSk();
          this.maxReconnect++;
        }else{
          this.$message.error("实时通知连接服务端失败，请刷新界面！");
          window.location.reload();
        }
      }
    },
    warnStatusChange(){
      this.activeClose = 0;
      let notice_s;
      if(this.warnStatus){
        notice_s = 1;
      }else{
        notice_s = 0;
      }
      let formData = new FormData();
      formData.append("warnNotice", notice_s);
      this.$http.post(
        "sysUser/updateWarnNotice",
        formData
      ).then(res => {
          if(res && res.data.result == "success"){
            window.sessionStorage.setItem("warnNotice",notice_s);
            if(this.websocket){
              if(notice_s == 1 && (this.websocket.readyState == 3 || this.websocket.readyState == 2)){
                this.connectionSk();
              }else if(notice_s == 0 && (this.websocket.readyState == 0 || this.websocket.readyState == 1)){
                this.activeClose = 1;
                this.websocket.close();
              }
            }else{
              if(notice_s == 1){
                this.connectionSk();
              }
            }
          }else{
            //提交失败需还原状态
            if(notice_s == 1){
              this.warnStatus = false;
            }else{
              this.warnStatus = true;
            }
            this.$message.error(res.data.message);
          }
      }).catch(err => {
          //提交失败需还原状态
          if(notice_s == 1){
            this.warnStatus = false;
          }else{
            this.warnStatus = true;
          }
          this.$message.error("更新实时通知请求异常！");
      })

    },
    warnWin(result){
      let htmlmsg ='<div style="margin: 5px;max-height: 300px;overflow: auto;"><font style="color: red;margin: 5px;line-break:anywhere;">'+result.data+'</font>共'+(result.data?result.data.split(",").length:0)+'个终端刚刚离线！</div>';
      if(result.data && (result.data.indexOf("发现") > -1 || result.data.indexOf("设备") > -1 || result.data.indexOf("插入") > -1)){//增加换行
        let h2 = "";
        let arr = result.data.split(",");
        for(let i=0;i<arr.length;i++){
          if(i == (arr.length - 1)){
            h2 += arr[i]
          }else{
            h2 += arr[i]+"</br>"
          }
        }
        htmlmsg ='<div style="margin: 5px;max-height: 300px;overflow: auto;"><font style="color: red;margin: 5px;line-break:anywhere;">'+h2+'</font></div>';
      }
      this.$notify({
        title: '警告 '+this.zycmUtils.dateFormatYMDHMS(new Date().getTime()),
        dangerouslyUseHTMLString: true,
        message: htmlmsg,
        type: 'warning',
        //duration:0
      });
      window.sessionStorage.setItem("notRead", 1);//标记有信息
    },
    openMessage(){
       setTimeout(() => {
            this.$router.push({
              path: '/messageNotify'
            })
          }, 500)
    },
    async selectCount(){
      let formData = new FormData();
      const { data: res } = await this.$http.post(
        "userNotify/selectCount",formData
      );
      if (res.result == "success") {
        this.notRead = res.data.notRead;
      } else {
        this.$message({
          type: "error",
          message: res.message,
        });
      }
      setInterval(()=>{
        let aa = window.sessionStorage.getItem("notRead");
        if(aa){
          if(aa > 0){
            this.notRead = aa;
          }else{
            this.notRead =0;
          }
        }
      },1000);
    }

  },
};
</script>

<style scoped lang="stylus">
.is-active img, .is-active .text {
  display: none;
}

.header {
  width: 100%;
  height: 12vh;
  display: flex;
  background: #36a9e1;

.logo {
    width: 200px;
    height: 12vh;
    color: #fff;
    text-indent: 15px;
    font-size: 18px;
    line-height: 30px;
    font-weight: 600;
    transition: 0.4s ease;

    &.is-active {
      width: 0px;
    }

    img {
      width: 45%;
     height: 45%;
    margin: 5% 35px 2%;
    }
  }

  .navbar {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10px;
    color: #fff;

    .btn {
      height: 50px;
      line-height: 50px;
      cursor: pointer;
      transition: 0.4s ease;

      &.is-active {
        transform: rotateY(180deg);
      }

      span {
        font-size: 28px;
        line-height: 50px;
        transition: 0.5s;
        color: #ffffff;
        font-weight: 400;
      }
    }

    .el-dropdown-link {
      color: #fff;
      font-weight: bold;
      cursor: pointer;
    }
  }
}

@media all and (max-width: 768px) {
  .header .logo.is-active {
    width: 0;
    overflow: hidden;
  }
}
</style>
